﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AutoDeploy.Client
{
    internal class ApiClient
    {
        private readonly HttpClient _client = new HttpClient();
        private readonly ProjectConfig _config;
        private string _serverUrl = "http://192.168.100.187:8080/";

        public ApiClient (ProjectConfig config)
        {
            if (!string.IsNullOrEmpty(config.ServerUrl))
            {
                _serverUrl = config.ServerUrl;
                if (!_serverUrl.EndsWith("/"))
                {
                    _serverUrl += "/";
                }
            }
            _client.BaseAddress = new Uri(_serverUrl);
            this._config = config;
        }

        /// <summary>
        /// 2
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public  async Task<string> UploadFileAsync(string filePath, string uploadFolder)
        {
            string apiUrl = "upload";

            // 读取文件到内存流
            using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                // 创建MultipartFormDataContent对象
                using var content = new MultipartFormDataContent();
                // 创建StreamContent对象并设置文件名
                var fileContent = new StreamContent(fileStream);
                fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data")
                {
                    Name = "file", // API期望的参数名称
                    FileName = Path.GetFileName(filePath)
                };

                // 添加文件内容到MultipartFormDataContent
                content.Add(fileContent);
                // 添加targetFolder参数
                content.Add(new StringContent(uploadFolder), "targetFolder");

                // 发送POST请求
                using var response = await _client.PostAsync(apiUrl, content);
                // 处理响应
                if (response.IsSuccessStatusCode)
                {
                    return "上传成功";
                }
                else
                {
                    return $"上传失败，状态码: {response.StatusCode}";
                }
            }
        }

        /// <summary>
        /// 3
        /// </summary>
        /// <param name="projectName"></param>
        /// <returns></returns>
       public  async Task<string> Pm2Execute(string projectName)
        {
            string command = string.Equals(_config.Environment, "Development", StringComparison.OrdinalIgnoreCase) ? "restart" : "reload";


            string apiUrl =  $"pm2/{command}/{projectName}";
            // 发送POST请求
            using var response = await _client.PostAsync(apiUrl, null);
            // 处理响应
            if (response.IsSuccessStatusCode)
            {
                return "重启完成";
            }
            else
            {
                return $"上传失败，状态码: {response.StatusCode}";
            }
        }
    }
}
